import { Component, OnInit, Input } from '@angular/core';
import { FormControl, NgForm } from '@angular/forms';

import { MaterialColorConfig } from '../../../configs/colors/material-color/material-color.config';

@Component({
    selector: 'op-input',
    templateUrl: './material-input.component.html',
    styleUrls: ['./material-input.component.scss']
})
export class MaterialInputComponent implements OnInit {
    @Input() ngForm: NgForm;
    @Input() reactiveFormControl: FormControl;
    @Input() maxLength: number;
    @Input() labelTitle: string;
    @Input() placeholder: string;
    @Input() type: string;
    @Input() color: string;
    isRequired: boolean;
    inputType: string;

    constructor() { }

    ngOnInit(): void {
        this.initializeProperties();
    }

    changeType(): void {
        this.inputType === 'text' ? this.inputType = 'password' : this.inputType = 'text';
    }

    protected initializeProperties(): void {
        this.isRequired = false;
        this.placeholder = this.placeholder || "";
        this.inputType = this.type || 'text';
        this.maxLength = this.maxLength || null;
        this.color = this.color || MaterialColorConfig.basic;

        // validator function returns object only contains required property. 
        // Whatever how many validators you've set.
        // We just want to get the validators from the FromControl instead of the duplicate @Input parameter.
        // By now Google only provides setValidators method. But no getValidators method.
        // More details check on https://github.com/angular/angular/issues/13461
        let validator = this.reactiveFormControl.validator ? this.reactiveFormControl.validator(this.reactiveFormControl) : null;
        this.isRequired = validator && validator.hasOwnProperty('required');
    }
}